const net = require("net");
const HOST = "127.0.0.1";
const PORT = 6868;

const server = net.createServer();
server.listen(PORT, HOST);

// 重要：双方建立链接时，会自动获得一个socket对象（std，socket描述符）
server.on("connection", (socket) => {
    // 远程客户端地址
    console.log(`connected:${socket.remoteAddress}:${socket.remotePort}`);
    // 本地服务端地址
    console.log(`local:${socket.localAddress}:${socket.localPort}`);
    // 向客户端发送数据
    socket.write("服：你好客户端");
    // 收到客户端数据时
    socket.on("data", (data) => {
        console.log(`${data}`);
    });
    // 客户端主动断连，触发end事件
    socket.on("end", (data) => {
        console.log(`客户端${socket.remoteAddress}:${socket.remotePort}已断连`);
    });
    // 如果链接断开，write方法就无效了
    setInterval(() => {
        socket.write(`服：定时消息${Date.now()}`);
    }, 1000);
});

console.log(`server listen on ${HOST}:${PORT}`);

